(function () {
    var utils = window.PpdRate = {},
        fenqienum = {
            all: 0,
            pay: 1,
            hand: 2
        };

    var _debx ,_handfee,_isPay,_payfee  ,_payCutFee,_payIsTop,_handIsTop,_handFeeTop,_payFeeTop,_handFeeNoTop,_payFeeNoTop,_publicTop;

    utils.type = function (o) {
        return Object.prototype.toString.call(o).slice(8, -1).toLowerCase();
    };

    utils.round = function (n) {
        return parseFloat(n * 1e12) / 1e12;
    };

    utils.toJson = function (str) {
        if (JSON.parse) {
            return JSON.parse(str);
        }

        return eval('(' + str + ')');
    };

    utils.formatObj = function (str, obj) {
        return str.replace(/\{([a-z\d]+)\}/ig, function (a, b) { return obj[b]; });
    };

    utils.formatNum = function (n) {
        var r = n + '';
        if (r.indexOf('.') === -1) {
            return r + '.00';
        }

        var arr = r.split('.');
        return arr[0] + '.' + (arr[1] + '00').substring(0, 2);
    };

    utils.formatNum2 = function (n) {
        return parseFloat(utils.formatNum(n)) || 0;
    };

    utils.formatDate = function (date, fmt) {
        var o = {
            "M+": date.getMonth() + 1,
            "d+": date.getDate(),
            "h+": date.getHours(),
            "m+": date.getMinutes(),
            "s+": date.getSeconds(),
            "q+": Math.floor((date.getMonth() + 3) / 3),
            "S": date.getMilliseconds()
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };

    utils.calfee = function (amount, month, yearRate, handRate, payRate, payType, isPay, fenqiType, clientCode, payCutFeeRatio, topNum,payTopNum) {
        amount = parseFloat(amount) || 0;
        month = parseInt(month) || 0;
        yearRate = parseFloat(yearRate) || 0;
        handRate = parseFloat(handRate) || 0;
        payRate = parseFloat(payRate) || 0;
        payType = parseInt(payType) || 0;
        isPay = parseInt(isPay) || 0;
        fenqiType = parseInt(fenqiType) || 0;
        clientCode = parseInt(clientCode) || 0;
        var args = [amount, month, yearRate, handRate, payRate, payType, isPay, fenqiType, clientCode, payCutFeeRatio, topNum,payTopNum];
        var result = {};

        _debx = debx(amount, yearRate, month);
        _handfee=amount * (handRate / 100);
        _isPay = payType === 1 || isPay === 1;
        _payfee = _isPay ?(amount * (payRate / 100)):0;
        _payCutFee = (_isPay&&payCutFeeRatio>0) ?(_payfee*payCutFeeRatio) :0;
        if(_payCutFee>0){
            _payfee = _payfee-_payCutFee;
        }
        /*_payIsTop = (payTopNum&&payTopNum>0);
        _handIsTop = (topNum&&topNum>0);*/

        _payIsTop = (payTopNum&&payTopNum>0&&payTopNum<month);
        _handIsTop = (topNum&&topNum>0&&topNum<month);

        _handFeeTop=utils.formatNum2(_handfee / topNum);
        _handFeeNoTop=utils.formatNum2(_handfee / month);
        _payFeeTop=utils.formatNum2(_payfee / payTopNum);
        _payFeeNoTop=utils.formatNum2(_payfee / month);
        _publicTop=Math.max(payTopNum||0,topNum||0);

        switch (fenqiType) {
            case fenqienum.all:
                result = calall.apply(this, args);
                break;
            case fenqienum.pay:
                result = calpay.apply(this, args);
                break;
            case fenqienum.hand:
                result = calhand.apply(this, args);
                break;
            default:
                result = {
                    MonthlyPayment: debx(amount, yearRate, month),
                    Balance: amount - getHandFee(amount, handRate) - getPayFee(amount, payRate)
                };
                break;
        }

        result.Balance = utils.formatNum(result.Balance);
        result.MonthRate = utils.formatNum(yearRate / 100 / 12);

        return result;
    };

    function debx(amount, yearRate, month) {
        var monthRate = yearRate / 100 / 12, p = parseFloat(Math.pow(1 + monthRate, month));
        return amount * monthRate * p / (p - 1);
    };

    function getHandFee(amount, handRate) {
        return utils.formatNum2((handRate / 100) * amount);
    }

    function getPayFee(amount, payRate) {
        return utils.formatNum2((payRate / 100) * amount);
    }

    /*加赔&手续费全分期*/
    function calall(amount, month, yearRate, handRate, payRate, payType, isPay, fenqiType, clientCode, payCutFeeRatio, topNum,payTopNum) {
        if(_payIsTop||_handIsTop){
            var a=0,b=0;

            if(_payIsTop&&!_handIsTop){
                a = utils.formatNum2(_debx) + _payFeeTop + _handFeeNoTop;
                b = utils.formatNum2(_debx) + _handFeeNoTop;
            }else if(!_payIsTop&&_handIsTop){
                a = utils.formatNum2(_debx) + _handFeeTop + _payFeeNoTop;
                b = utils.formatNum2(_debx) + _payFeeNoTop;
            }else{
                a = utils.formatNum2(_debx) + _handFeeTop + _payFeeTop;
                b = utils.formatNum2(_debx);
            }

            return {
                FeeType: 2,
                Num: topNum,
                PayNum:payTopNum,
                MonthlyPayment1: a,
                MonthlyPayment2: b,
                Balance: amount - utils.formatNum2(_payCutFee)
            };
        }else{
            var c = utils.formatNum2(_debx) + utils.formatNum2((_handfee + _payfee) / month);
            return {
                MonthlyPayment: utils.round(c),
                Balance: amount - utils.formatNum2(_payCutFee)
            };
        }
    }

    /*加赔分期,手续费一次收*/
    function calpay(amount, month, yearRate, handRate, payRate, payType, isPay, fenqiType, clientCode, payCutFeeRatio, topNum,payTopNum) {
        var a,b,r={};
        if(_payIsTop){
             a = utils.formatNum2(_debx) + _payFeeTop ;
             b = utils.formatNum2(_debx) ;

            r= {
                FeeType: 2,
                Num: _publicTop,
                MonthlyPayment1: a,
                MonthlyPayment2: b
            };
        }else{
            r= {
                MonthlyPayment:_debx+_payFeeNoTop
            };
        }

        r.Balance= amount - utils.formatNum2(_handfee)-utils.formatNum2(_payCutFee);
        return r;
    }

    function calhand(amount, month, yearRate, handRate, payRate, payType, isPay, fenqiType, clientCode, payCutFeeRatio, topNum,payTopNum) {
        var bx = debx(amount, yearRate, month),
            handfee = amount * (handRate / 100),
            payfee = getPayFee(amount, payRate);

        if (topNum && topNum > 0 && topNum < month) {
            var a = utils.formatNum2(bx) + utils.formatNum2(handfee / topNum);
            var b = utils.round(bx);
            return {
                FeeType: 2,
                MonthlyPayment1: a,
                MonthlyPayment2: b,
                Num: topNum,
                PayNum:payTopNum,
                Balance: amount - payfee
            };
        } else {
            var c = utils.formatNum2(bx) + utils.formatNum2(handfee / month);
            return {
                MonthlyPayment: utils.round(c),
                Balance: amount - payfee
            };
        }
    }

})(window, undefined);

function getExtendData(data,month,key){
    for (var i = 0; i < data.length; i++) {
        if (data[i].Month === parseInt(month)) {
            return data[i][key];
        }
    }
    return 0;
}

var getlist = function(amount, month, yearRate, handRate, payRate, payType, isPay, fenqiType, clientCode) {
    var args = [amount, month, yearRate, handRate, payRate, payType, isPay, fenqiType, clientCode];
    args.push(getExtendData(payCutFeeData,month,'PayFeeCut'));
    args.push(getExtendData(feeNums,month,'Num'));
    args.push(getExtendData(payNums,month,'Num'));

    var r = PpdRate.calfee.apply(this, args), arr = [],datelist=getDateList(month);

    for (var i = 1; i <= month; i++) {
        var item = { Sub: 0, Month: i };
        if (r.FeeType === 2) {
          /*  if (r.PayNum > r.Num) {
                
            }*/
            var n = r.PayNum <r.Num ? r.PayNum : r.Num;
            if (i <= n) {
                item.Amount = PpdRate.formatNum(r.MonthlyPayment1);
            } else {
                item.Amount = PpdRate.formatNum(r.MonthlyPayment2);
                item.Sub = PpdRate.formatNum(r.MonthlyPayment1 - r.MonthlyPayment2);
            }
        } else {
            item.Amount = PpdRate.formatNum(r.MonthlyPayment);
        }
        item.Date = datelist[i - 1];
        arr.push(item);
    }

    return { fee: r, list: arr };
};

function getDateList(m) {
    var nowDate = new Date(),
        todayNum = nowDate.getDate(),
        year = nowDate.getFullYear(),
        month = nowDate.getMonth() + 1,
        arr = [],crtMonthMaxDay;

    for (var index = 1; index <= m; index++) {
        month++;
        if (month > 12) {
            year++;
            month = 1;
        }

        switch (month) {
            case 2:
                crtMonthMaxDay = isLeapYear(year) ? 29 : 28;
                break;
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                crtMonthMaxDay = 31;
                break;
            default:
                crtMonthMaxDay = 30;
                break;
        }
        var dateNum = todayNum <= crtMonthMaxDay ? todayNum : crtMonthMaxDay;
        arr.push(year + '.' + month + '.' + (dateNum < 10 ? ('0' + dateNum) : dateNum));
    }

    return arr;
}

function isLeapYear(year) {
    var a1 = year % 4 == 0;
    var a2 = year % 100 != 0;
    var a3 = year % 400 == 0;
    return (a1 && a2) || a3;
}

function calresult() {
    var r = getlist.apply(this, arguments),arr=[];
    for (var i = 0; i < r.list.length; i++) {
        arr.push('{"Month":'+r.list[i].Month+',"Amount":'+r.list[i].Amount+',"Sub":'+r.list[i].Sub+',"Date":"'+r.list[i].Date+'"}');
    }
    var feeArr = ['{'];
    feeArr.push('"ItemList":[' + arr.join(',') + ']');
    feeArr.push(',"CityLoan":{"ShowList":1,"FeeType":'+(r.fee.FeeType||1)+',"MonthlyPayment1":'+(r.fee.FeeType===2?r.fee.MonthlyPayment1:r.fee.MonthlyPayment)+',"MonthlyPayment2":'+(r.fee.MonthlyPayment2||0)+',"Num":'+(r.fee.Num||0)+'}');
    feeArr.push(',"HuanLoan":{"ShowList":1,"FeeType":'+(r.fee.FeeType||1)+',"MonthlyPayment1":'+(r.fee.FeeType===2?r.fee.MonthlyPayment1:r.fee.MonthlyPayment)+',"MonthlyPayment2":'+(r.fee.MonthlyPayment2||0)+',"Num":'+(r.fee.Num||0)+'}');
    feeArr.push('}');

    r.fee.Balance = PpdRate.formatNum(r.fee.Balance);
    if(r.fee.FeeType===2) {
        r.fee.MonthlyPayment1 = PpdRate.formatNum(r.fee.MonthlyPayment1);
        r.fee.MonthlyPayment2 = PpdRate.formatNum(r.fee.MonthlyPayment2);
        var n =r.fee.PayNum <r.fee.Num ? r.fee.PayNum : r.fee.Num;
        return r.fee.MonthlyPayment1 + '元（第' + (n+1) + '期起月还' + r.fee.MonthlyPayment2 + '元）@@' + r.fee.Balance + '元@@' + feeArr.join('');
    }

    r.fee.MonthlyPayment = PpdRate.formatNum(r.fee.MonthlyPayment);
    return r.fee.MonthlyPayment + '元@@' + r.fee.Balance + '元@@' + feeArr.join('');
};

function calforios() {
    var r = calresult.apply(this, arguments);
    window.location.href = 'objc:doFunc2:' + r;
};

function calforandroid() {
    var r = calresult.apply(this, arguments);
    window.ppdai.cbkrate(r);
};
